/*
 * @Description: 路由管理
 * @Autor: 万洲
 * @Date: 2022-10-17 09:50:06
 * @LastEditors: 万洲
 * @LastEditTime: 2022-11-22 16:42:48
 */
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import $$ from "@/utils/wzUtils"
import useUserStore from '@/store/useUserStore'

const routes: Array<RouteRecordRaw> = []

let getWebFiles = require["context"]("./Modules", true, /\.ts$/)
getWebFiles.keys().forEach((key: string) => {
  routes.push(...getWebFiles(key).default)
})

const router = createRouter({
  history: createWebHistory(window.__POWERED_BY_QIANKUN__ ? '/web' : '/'),
  routes: routes,
});
// const path = "/Login/index"
// router.addRoute("/", {
//   ...(() => { const path = "/login"; return { path, name: path } })(),
//   component: () => import(`@/views${path}`),
// })

export const totalList = [
  {
    name: "工作台",
    path: "/index",
    type: "menu",
    component: "/Index",
  },
  {
    name: "系统管理",
    path: "System",
    type: "catalogue",
    children: [
      {
        name: "用户管理",
        path: "/System/User/index",
        component: "/System/User/index",
        type: "menu",
      },
      {
        name: "角色管理",
        path: "/System/Role/index",
        component: "/System/Role/index",
        type: "menu",
      },
    ]
  }
]

/**
 * 树状结构拍平
 * @param children 
 * @returns 
 */
export const getFlatTree = <T>(children: T[], childrenName: string = "children"): T[] => {
  return children.reduce((pre, cur) => {
    let childrenList = cur[childrenName] || []
    let result: any = [...pre, cur, ...getFlatTree(childrenList)];
    return result;
  }, []);
};

const menuList = getFlatTree(totalList).filter(v => v.type === "menu")

/**
 * 路由加载前
 */
let addCount = 0
router.afterEach(() => {
})
router.beforeEach((to, from, next) => {

  const userStore = useUserStore()
  if (!userStore.userToken && to.name !== '/login') {
    // 将用户重定向到登录页面
    return next({ name: '/login' })
  }
  if (addCount === 0 && menuList[0]) {
    menuList.forEach((item) => {
      router.addRoute("Layout", {
        path: item.path,
        name: item.path,
        component: () => import(`@/views${item.component}`)
      })
    })
    addCount++
    return next({ ...to, replace: true })
  }
  next()
})
// 路由加载后
router.afterEach(() => {
  NProgress.done()
})
export default router
